import { defineStore } from 'pinia'

export type StdfKey = {
    lotId: string;
    wfNo: string;
    cpNo: string;
    rpNo: string;
}

export type StdfRecord = StdfKey & {
    md5: string;
    dbPath: string;
    fromCache: boolean;
    time: number;
}

function keyString(k: StdfKey) {
  return `${k.lotId}__${k.wfNo}__${k.cpNo}__${k.rpNo}`;
}

export const useStdfStore = defineStore('stdf', {
  state: () => ({
    current: null as StdfRecord | null,
    map: {} as Record<string, StdfRecord>
  }),
  actions: {
    load() {
      const raw = localStorage.getItem('stdf-map');
      if (raw) this.map = JSON.parse(raw);
      const cur = localStorage.getItem('stdf-current');
      if (cur) this.current = JSON.parse(cur);
    },
    save() {
      localStorage.setItem('stdf-map', JSON.stringify(this.map));
      if (this.current) localStorage.setItem('stdf-current', JSON.stringify(this.current));
    },
    setCurrent(rec: StdfRecord) {
      this.current = rec;
      this.map[keyString(rec)] = rec;
      this.save();
    },
    getByKey(k: StdfKey) {
      return this.map[keyString(k)] ?? null;
    }
  }
});